import 'package:common_utils/common_utils.dart';
import 'package:extended_text/extended_text.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_message_letter_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/special_text/my_special_text_span_builder.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';


///私信
class MessageLetterList extends StatefulWidget {

  const MessageLetterList({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new MessageLetterListState();
  }
}

class MessageLetterListState extends State<MessageLetterList> with AutomaticKeepAliveClientMixin<MessageLetterList> {

  HttpRepository httpRepository;
  int size = 0;
  bool isLoadedData = false;
  bool deletable = false;

  int requestCount;
  int totalResults;
  int responseCount;
  String pageToken;

  double paddingParentHorizontal = Dimens.gap_activity_horizontal;
  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscMessageLetterEntity> list;

  RefreshController controller = RefreshController(initialRefresh: true);


  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return SmallWidgets.buildLine();
        },
        itemCount: isLoadedData && size == 0? 1 : size,
      ),
    );
  }

  buildListItem(int index){
    OscMessageLetterEntity item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
//        jump2PageForResult(TweetDetail(tweet: item, expandedHeight: height,));
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(paddingParentHorizontal),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            OscPortraitWidget(id: item.sender.id, portraitImageUrl: item.sender.portrait,),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: Dimens.gap_view_bigger),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(item.sender.name, style: MyTextStyle.USER_LIST_TITLE,),
                        ),
                        Text(TimelineUtil.formatByDateTime(DateTime.parse(item.pubDate), dayFormat: DayFormat.Full),
                          style: MyTextStyle.LIST_BOTTOM,),
                      ],
                    ),
                    SmallWidgets.buildLineBigger(color: Colors.transparent,),
                    buildContentText(item.content),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildContentText(String text){
    return ExtendedText(
      text,
      style: MyTextStyle.TWEET_CONTENT,
      onSpecialTextTap: (dynamic parameter) {},
      specialTextSpanBuilder: MySpecialTextSpanBuilder(),
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
    );
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    await httpRepository.getMyMassageLetters(pageToken: pageToken).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscMessageLetterEntity> result = resp.result;
        if(result != null){
          List<OscMessageLetterEntity> tempItems = result.items;
          responseCount = result.responseCount;
          requestCount = result.requestCount;
          if(StringUtil.isEmpty(pageToken)){
            list = tempItems;
          } else {
            list.addAll(tempItems);
          }
          pageToken = result.nextPageToken;
          size = list?.length??0;
          if(responseCount < requestCount || size == result.totalResults){
            controller.loadNoData();
          } else {
            controller.loadComplete();
          }
        }
      }
    });
    if(mounted){
      setState(() {
        controller.refreshCompleted();
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
